/**
 * ====================================================
 * 文件名称: BulkstockCategoryActionApiImpl.java
 * 修订记录：
 * No    日期				作者(操作:具体内容)
 * 1.    2015年9月23日			chenxy(创建:创建文件)
 * ====================================================
 * 类描述：(说明未实现或其它不应生成javadoc的内容)
 */
package com.yuexunit.finance.bulkstock.action.v1;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yuexunit.core.ConfigPropertites;
import com.yuexunit.finance.bulkstock.action.v1.dto.BulkstockCategoryCastor;
import com.yuexunit.finance.bulkstock.action.v1.model.BulkstockCategory;
import com.yuexunit.finance.bulkstock.action.v1.model.BulkstockCategoryDetail;
import com.yuexunit.finance.bulkstock.action.v1.model.BulkstockInfoDetail;
import com.yuexunit.finance.bulkstock.entity.BulkstockCategoryEntity;
import com.yuexunit.finance.bulkstock.entity.BulkstockInfoEntity;
import com.yuexunit.finance.bulkstock.entity.MaterialTemplateEntity;
import com.yuexunit.finance.bulkstock.entity.lexicon.MaterialTemplateEnum;
import com.yuexunit.finance.bulkstock.entity.lexicon.MeasurementEnum;
import com.yuexunit.finance.bulkstock.service.BulkstockCategoryService;
import com.yuexunit.finance.bulkstock.service.BulkstockInfoService;
import com.yuexunit.finance.bulkstock.service.MaterialTemplateService;
import com.yuexunit.finance.common.httpclient.HttpClientHelper;
import com.yuexunit.finance.common.util.BeanUtils;
import com.yuexunit.finance.common.util.DateUtils;
import com.yuexunit.finance.project.entity.lexicon.ProductTypeEnum;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.inject.annotation.Implements;
import com.yuexunit.page.PageCriteria;
import com.yuexunit.page.PageList;
import com.yuexunit.persist.annotation.Transactional;
import com.yuexunit.persist.hibernate.SessionRepository;
import com.yuexunit.util.StringUtil;

/**
 * @ClassName: BulkstockCategoryActionApiImpl
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author chenxy
 * @date 2015年9月23日 下午7:30:41
 */
@Implements(BulkstockCategoryActionApi.class)
public class BulkstockCategoryActionApiImpl implements BulkstockCategoryActionApi {

	public static Logger logger = LoggerFactory.getLogger(BulkstockCategoryActionApiImpl.class);
	
	private BulkstockCategoryService bulkstockCategoryService = ComponentFactory.loadClass(BulkstockCategoryService.class);

	private MaterialTemplateService materialTemplateService = ComponentFactory.loadClass(MaterialTemplateService.class);

	private BulkstockInfoService bulkstockService = ComponentFactory.loadClass(BulkstockInfoService.class);

	@Transactional
	@Override
	public void syncBulkstockCategory() {
		List<BulkstockCategoryEntity> categories = BulkstockCategoryCastor.fromSyncBulkstockCategory();
		for (BulkstockCategoryEntity category : categories) {
			bulkstockCategoryService.createBulkstockCategory(category);
		}
	}

	@Transactional
	@Override
	public void disableBulkstockCategory(Long bulkstockCategoryId) {
		bulkstockCategoryService.disableBulkstockCategory(bulkstockCategoryId);
	}

	@Override
	public PageList<BulkstockCategory> inquireBulkstockCategoryPageListByKeyword(String keyword, PageCriteria page) {
		PageList<BulkstockCategoryEntity> pageList = bulkstockCategoryService.inquireBulkstockCategoryList(keyword, page);
		PageList<BulkstockCategory> list = new PageList<>(page, pageList.getTotalRecordCount());
		for (BulkstockCategoryEntity entity : pageList) {
			BulkstockCategory bulkstockCategory = BulkstockCategoryCastor.toBulkstockCategory(entity, false);
			list.add(bulkstockCategory);
		}
		return list;
	}

	@Override
	public BulkstockCategoryDetail inquireBulkstockCategoryDetail(Long bulkstockCategoryId) {
		BulkstockCategoryEntity bulkstockCategoryEntity = bulkstockCategoryService.inquireBulkstockCategory(bulkstockCategoryId);
		return BulkstockCategoryCastor.toBulkstockCategoryDetail(bulkstockCategoryEntity);
	}

	@Override
	public PageList<BulkstockCategory> inquireBulkstockCategoryPageList(Long bulkstockCategoryId, String beginDate, String endDate, Boolean activeState, String categoryName, Integer productType, PageCriteria page) {
		Date beginUpdateDate = DateUtils.formatBeginDay(beginDate);
		Date endUpdateDate = DateUtils.formatEndDay(endDate);
		Boolean isFactoring = Boolean.FALSE;
		if (ProductTypeEnum.valueOf(productType) == ProductTypeEnum.FREIGHT_FACTORING) {
			isFactoring = Boolean.TRUE;
		}
		if (null == productType) {
			isFactoring = null;
		}
		PageList<BulkstockCategoryEntity> pageList = bulkstockCategoryService.inquireBulkstockCategoryList(bulkstockCategoryId, beginUpdateDate, endUpdateDate, activeState, categoryName, isFactoring, page);
		PageList<BulkstockCategory> resultList = new PageList<>(page, pageList.getTotalRecordCount());
		for (BulkstockCategoryEntity entity : pageList) {
			resultList.add(BulkstockCategoryCastor.toBulkstockCategory(entity, true));
		}
		return resultList;
	}

	@Override
	public void activeBulkstockCategory(Long bulkstockCategoryId) {
		bulkstockCategoryService.activeBulkstockCategory(bulkstockCategoryId);
	}

	@Override
	public void deprecatedBulkstockCategory(Long bulkstockCategoryId) {
		bulkstockCategoryService.deprecatedBulkstockCategory(bulkstockCategoryId);
	}

	@Transactional
	@Override
	public void updateMaterialTemplate(String categoryName, Long bulkstockCategoryId, Long[] templateIds, String[] templateNames, Integer[] checkedRequireds) {
		BulkstockCategoryEntity categoryEntity = new BulkstockCategoryEntity();
		categoryEntity.setCategoryName(categoryName);
		categoryEntity.setBulkstockCategoryId(bulkstockCategoryId);
		bulkstockCategoryService.updateBulkstockCategory(categoryEntity);
		List<MaterialTemplateEntity> materialTemplateEntities = materialTemplateService.inquireMaterialTemplateList(bulkstockCategoryId);
		Set<Long> templateIdSet = new HashSet<>();
		CollectionUtils.addAll(templateIdSet, templateIds);
		for (int i = 0; i < templateNames.length; i++) {
			MaterialTemplateEntity entity = new MaterialTemplateEntity();
			entity.setTemplateId(templateIds[i]);
			entity.setTemplateName(templateNames[i]);
			entity.setCheckedRequired(MaterialTemplateEnum.valueOf(checkedRequireds[i]));
			entity.setBulkstockCategoryId(bulkstockCategoryId);
			if (entity.getTemplateId() == null || entity.getTemplateId() == 0) {
				materialTemplateService.createMaterialTemplate(entity);
			} else {
				materialTemplateService.updateMaterialTemplate(entity);
			}
		}
		for (MaterialTemplateEntity entity : materialTemplateEntities) {
			if (!templateIdSet.contains(entity.getTemplateId())) {
				materialTemplateService.disableMaterialTemplate(entity.getTemplateId());
			}
		}
	}

	@Override
	@Transactional
	public Long createBulkstockCategory(String categoryName, Boolean isFactoring, Long[] templateIds, String[] templateNames, Integer[] checkedRequireds) {
		BulkstockCategoryEntity entity = new BulkstockCategoryEntity();
		entity.setCategoryName(categoryName);
		entity.setIsFactoring(isFactoring);
		Long bulkstockCategoryId =  bulkstockCategoryService.createBulkstockCategory(entity);

		List<MaterialTemplateEntity> materialTemplateEntities = materialTemplateService.inquireMaterialTemplateList(bulkstockCategoryId);
		Set<Long> templateIdSet = new HashSet<>();
		CollectionUtils.addAll(templateIdSet, templateIds);
		for (int i = 0; i < templateNames.length; i++) {
			MaterialTemplateEntity me = new MaterialTemplateEntity();
			me.setTemplateId(templateIds[i]);
			me.setTemplateName(templateNames[i]);
			me.setCheckedRequired(MaterialTemplateEnum.valueOf(checkedRequireds[i]));
			me.setBulkstockCategoryId(bulkstockCategoryId);
			if (me.getTemplateId() == null || me.getTemplateId() == 0) {
				materialTemplateService.createMaterialTemplate(me);
			} else {
				materialTemplateService.updateMaterialTemplate(me);
			}
		}
		for (MaterialTemplateEntity me : materialTemplateEntities) {
			if (!templateIdSet.contains(me.getTemplateId())) {
				materialTemplateService.disableMaterialTemplate(me.getTemplateId());
			}
		}

		return bulkstockCategoryId;
	}

	// ======================================================================================================================//
	@Override
	public PageList<BulkstockInfoDetail> inquireBulkstockPageList(Long bulkstockCategoryId, String keyword, PageCriteria page) {
		PageList<BulkstockInfoEntity> pageList = bulkstockService.inquireBulkstockInfoPageList(bulkstockCategoryId, null, keyword, keyword, true, page);
		PageList<BulkstockInfoDetail> resultList = new PageList<>(page, pageList.getTotalRecordCount());
		for (BulkstockInfoEntity entity : pageList) {
			resultList.add(BulkstockCategoryCastor.toBulkstockInfo(entity));
		}
		return resultList;
	}
	

	@Override
	public List<BulkstockInfoDetail> inquireEnterpriseBulkstockList(Long enterpriseId, String keyword) {
		List<BulkstockInfoDetail> bids = new ArrayList<>();
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT DISTINCT a.BULKSTOCK_INFO_ID, a.BULKSTOCK_NAME, a.SPECIFICATION FROM fin_finance_bulkstock a, fin_finance_application b WHERE a.FINANCE_ID = b.FINANCE_ID");
		if (enterpriseId != null) {
			sql.append(" AND b.ENTERPRISE_ID = ").append(enterpriseId);
		}
		if (StringUtil.isNotBlank(keyword)) {
			sql.append(" AND a.BULKSTOCK_NAME LIKE ").append("%" + keyword + "%");
		}
		Session session = SessionRepository.getCurrentSession();
		
		List<Object> datas = session.createSQLQuery(sql.toString()).addScalar("BULKSTOCK_INFO_ID").addScalar("BULKSTOCK_NAME").addScalar("SPECIFICATION").list();
		for (Object l : datas) {
			Object[] os = (Object[]) l;
			BulkstockInfoDetail bid = new BulkstockInfoDetail();
			bid.setBulkstockInfoId(((BigInteger)os[0]).longValue());
			bid.setBulkstockName((String)os[1]);
			bid.setSpecificationName((String)os[2]);
			bids.add(bid);
		}
		SessionRepository.closeCurrentSession();
		
		return bids;
	}

	@Override
	public PageList<BulkstockInfoDetail> inquireBulkstockInfoPageList(Long bulkstockCategoryId, String categoryName, String bulkstockName, String specificationName, Boolean activeState, PageCriteria page) {
		PageList<BulkstockInfoEntity> pageList = bulkstockService.inquireBulkstockInfoPageList(bulkstockCategoryId, categoryName, bulkstockName, specificationName, activeState, page);
		PageList<BulkstockInfoDetail> resultList = new PageList<>(page, pageList.getTotalRecordCount());
		for (BulkstockInfoEntity entity : pageList) {
			resultList.add(BulkstockCategoryCastor.toBulkstockInfo(entity));
		}
		return resultList;
	}

	@Transactional
	@Override
	public void syncBulkstockInfo(Long bulkstockCategoryId) {
		BulkstockCategoryEntity category = bulkstockCategoryService.inquireBulkstockCategory(bulkstockCategoryId);
		List<BulkstockInfoEntity> bulkstocks = BulkstockCategoryCastor.fromSyncBulkstockInfo(category);
		for (BulkstockInfoEntity bulkstock : bulkstocks) {
			bulkstockService.createBulkstockInfo(bulkstock);
		}
	}
	
	@Override
	public void syncCargoInfo(Long bulkstockInfoId) {
		BulkstockInfoEntity bulkstockInfo = bulkstockService.inquireBulkstockInfo(bulkstockInfoId);
		//同步商品信息到仓储系统
		String url = ConfigPropertites.getProperties("finance.syncCargoInfo.service");
		Map<String, String> param = new HashMap<>();
		param.put("goods.goodsType", bulkstockInfo.getCategoryName());
		param.put("goods.goodsName", bulkstockInfo.getBulkstockName());
		param.put("goods.relation_id", bulkstockInfo.getBulkstockInfoId().toString());
		param.put("goods.goodscode", bulkstockInfo.getBulkstockNumber());
		param.put("goods.specification", bulkstockInfo.getSpecificationName());
		param.put("goods.net_weight", bulkstockInfo.getNetWeight().toString());
		param.put("goods.rough_weight", bulkstockInfo.getNetWeight().toString());
		param.put("goods.goods_volume", bulkstockInfo.getVolume().toString());
		param.put("goods.origin", bulkstockInfo.getOriginalPlace());
		param.put("goods.unit", bulkstockInfo.getCountingUnit());
		param.put("goods.smallunit", bulkstockInfo.getReducedUnit());
		param.put("goods.conversion", bulkstockInfo.getConversionRelation());
		param.put("goods.price", bulkstockInfo.getPrice().toString());
		String responseText = HttpClientHelper.post(url, param);
		logger.info("url:" + url);
		logger.info("params:" + param);
		logger.info("responseText" + responseText);
	}

	@Transactional
	@Override
	public void updateBulkstockInfo(Long bulkstockInfoId, String bulkstockName, String bulkstockNumber, Long bulkstockCategoryId,
			String specificationName, String bulkstockGrade, BigDecimal grossWeight,
			BigDecimal netWeight, BigDecimal volume, BigDecimal price, String originalPlace, String countingUnit, String reducedUnit,
			String conversionRelation) {
		
		BulkstockInfoEntity bulkstockInfo = bulkstockService.inquireBulkstockInfo(bulkstockInfoId);
		
		bulkstockInfo.setBulkstockName(bulkstockName);
		bulkstockInfo.setBulkstockNumber(bulkstockNumber);
		bulkstockInfo.setBulkstockCategoryId(bulkstockCategoryId);
		bulkstockInfo.setCategoryName(bulkstockCategoryService.inquireBulkstockCategory(bulkstockCategoryId).getCategoryName());
		bulkstockInfo.setSpecificationName(specificationName);
		bulkstockInfo.setMeasurement(MeasurementEnum.valueOf(2));
		bulkstockInfo.setConversionFactor(new BigDecimal(1));
		bulkstockInfo.setBulkstockGrade(bulkstockGrade);
		bulkstockInfo.setGrossWeight(grossWeight);
		bulkstockInfo.setNetWeight(netWeight);
		bulkstockInfo.setVolume(volume);
		bulkstockInfo.setOriginalPlace(originalPlace);
		bulkstockInfo.setCountingUnit(countingUnit);
		bulkstockInfo.setReducedUnit(reducedUnit);
		bulkstockInfo.setPrice(price);
		bulkstockInfo.setConversionRelation(conversionRelation);
		
		bulkstockService.renovateBulkstockInfo(bulkstockInfo);
		bulkstockService.uniqueness(bulkstockName,specificationName);
		
		//同步商品信息到仓储系统
		String url = ConfigPropertites.getProperties("finance.syncCargoInfo.service");
		Map<String, String> param = new HashMap<>();
		param.put("goods.goodsType", bulkstockInfo.getCategoryName());
		param.put("goods.goodsName", bulkstockInfo.getBulkstockName());
		param.put("goods.relation_id", bulkstockInfo.getBulkstockInfoId().toString());
		param.put("goods.goodscode", bulkstockInfo.getBulkstockNumber());
		param.put("goods.specification", bulkstockInfo.getSpecificationName());
		param.put("goods.net_weight", bulkstockInfo.getNetWeight().toString());
		param.put("goods.rough_weight", bulkstockInfo.getNetWeight().toString());
		param.put("goods.goods_volume", bulkstockInfo.getVolume().toString());
		param.put("goods.origin", bulkstockInfo.getOriginalPlace());
		param.put("goods.unit", bulkstockInfo.getCountingUnit());
		param.put("goods.smallunit", bulkstockInfo.getReducedUnit());
		param.put("goods.conversion", bulkstockInfo.getConversionRelation());
		param.put("goods.price", bulkstockInfo.getPrice().toString());
		String responseText = HttpClientHelper.post(url, param);
		logger.info("url:" + url);
		logger.info("params:" + param);
		logger.info("responseText" + responseText);
	}

	@Transactional
	@Override
	public String createBulkstockInfo(String bulkstockName, String bulkstockNumber, Long bulkstockCategoryId, Long bulkstockInfoId,
			String specificationName, String bulkstockGrade, BigDecimal grossWeight,
			BigDecimal netWeight, BigDecimal volume, BigDecimal price, String originalPlace, String countingUnit, String reducedUnit,
			String conversionRelation) {
		
		BulkstockInfoEntity sourceInfo = bulkstockService.inquireBulkstockInfo(bulkstockInfoId);
		BulkstockInfoEntity targetInfo = new BulkstockInfoEntity();
		BeanUtils.copyProperties(sourceInfo, targetInfo);
		targetInfo.setBulkstockName(bulkstockName);
		targetInfo.setBulkstockNumber(bulkstockNumber);
		targetInfo.setBulkstockCategoryId(bulkstockCategoryId);
		targetInfo.setCategoryName(bulkstockCategoryService.inquireBulkstockCategory(bulkstockCategoryId).getCategoryName());
		targetInfo.setBulkstockInfoId(null);
		targetInfo.setSpecificationName(specificationName);
		targetInfo.setMeasurement(MeasurementEnum.valueOf(2));
		targetInfo.setConversionFactor(new BigDecimal(1));
		targetInfo.setBulkstockGrade(bulkstockGrade);
		targetInfo.setGrossWeight(grossWeight);
		targetInfo.setNetWeight(netWeight);
		targetInfo.setVolume(volume);
		targetInfo.setOriginalPlace(originalPlace);
		targetInfo.setCountingUnit(countingUnit);
		targetInfo.setReducedUnit(reducedUnit);
		targetInfo.setPrice(price);
		targetInfo.setConversionRelation(conversionRelation);
		bulkstockService.createBulkstockInfo(targetInfo);
		bulkstockService.uniqueness(bulkstockName,specificationName);
		
		//同步商品信息到仓储系统
		String url = ConfigPropertites.getProperties("finance.syncCargoInfo.service");
		Map<String, String> param = new HashMap<>();
		param.put("goods.goodsType", targetInfo.getCategoryName());
		param.put("goods.goodsName", targetInfo.getBulkstockName());
		param.put("goods.relation_id", targetInfo.getBulkstockInfoId().toString());
		param.put("goods.goodscode", targetInfo.getBulkstockNumber());
		param.put("goods.specification", targetInfo.getSpecificationName());
		param.put("goods.net_weight", targetInfo.getNetWeight().toString());
		param.put("goods.rough_weight", targetInfo.getNetWeight().toString());
		param.put("goods.goods_volume", targetInfo.getVolume().toString());
		param.put("goods.origin", targetInfo.getOriginalPlace());
		param.put("goods.unit", targetInfo.getCountingUnit());
		param.put("goods.smallunit", targetInfo.getReducedUnit());
		param.put("goods.conversion", targetInfo.getConversionRelation());
		param.put("goods.price", targetInfo.getPrice().toString());
		String responseText = HttpClientHelper.post(url, param);
		logger.info("url:" + url);
		logger.info("params:" + param);
		logger.info("responseText" + responseText);
		
		return targetInfo.getBulkstockInfoId().toString();
	}

	@Override
	public void activeBulkstockInfo(Long bulkstockInfoId) {
		bulkstockService.activeBulkstockInfo(bulkstockInfoId);
	}

	@Override
	@Transactional
	public void deprecatedBulkstockInfo(Long bulkstockInfoId) {
		BulkstockCategoryCastor.existUnfinishFinance(bulkstockInfoId);
		bulkstockService.deprecatedBulkstockInfo(bulkstockInfoId);
	}

	@Override
	public BulkstockInfoDetail inquireBulkstockInfo(Long bulkstockInfoId) {
		BulkstockInfoEntity bie = bulkstockService.inquireBulkstockInfo(bulkstockInfoId);
		BulkstockInfoDetail bid = BulkstockCategoryCastor.toBulkstockInfo(bie);
		return bid;
	}
}
